//
//  RegitsterViewController.m
//  copyrightTrading
//
//  Created by 郭子一 on 2020/10/5.
//  Copyright © 2020 郭子一. All rights reserved.
//

#import "RegitsterViewController.h"

@interface RegitsterViewController ()
@property (nonatomic, strong) UITextField *phoneNumTextF;  // 手机号
@property (nonatomic, strong) UITextField *userNameTextF;  // 用户名
@property (nonatomic, strong) UITextField *verificationCodeTextF;  // 验证码
@property (nonatomic, strong) UIButton *verificationBtn;  // 验证码
@property (nonatomic, strong) UITextField *passwordTextF;  // 密码
@property (nonatomic, strong) UITextField *ensurePasswordTextF;  // 确认密码
@property (nonatomic, strong) UIView *sliderBGView;  //
@property (nonatomic, strong) UIView *sliderView;  //
@property (nonatomic, strong) UIImageView *sliderImg;  //

@property (nonatomic, assign) BOOL isVerification;  // 是否滑动验证过
@property (nonatomic, assign) BOOL isSelectProtocal;  // 是否同意协议
@end

@implementation RegitsterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isVerification = NO;
    self.isSelectProtocal = NO;
}

- (void)setupUI
{
    UIScrollView *bgScrollview = [[UIScrollView alloc] init];
    bgScrollview.showsVerticalScrollIndicator = NO;
    bgScrollview.bounces = NO;
    [self.view addSubview:bgScrollview];
    [bgScrollview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kDeviceWidth);
        make.top.equalTo(self.view);
        make.height.mas_equalTo(KDeviceHeight);
    }];
    
    UIImageView *bgImg = [[UIImageView alloc] init];
    bgImg.image = [UIImage imageNamed:@"loginBGImg"];
    bgImg.userInteractionEnabled = YES;
    [bgScrollview addSubview:bgImg];
    [bgImg mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.offset(0);
        make.width.mas_equalTo(kDeviceWidth);
        make.top.left.offset(0);
    }];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.hitEdgeInsets = UIEdgeInsetsMake(-15, -15, -15, -15);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"whiteBack"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bgImg addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(59);
        make.left.offset(26);
        make.width.height.mas_equalTo(25);
    }];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"用户注册";
    titleLabel.font = JSS_MEDIUM_FONT(34);
    titleLabel.textColor = RGB_VALUE(0xFFFFFF);
    [bgImg addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(107);
        make.left.offset(35);
        make.right.offset(-35);
        make.height.mas_equalTo(48);
    }];
    
    self.phoneNumTextF = [InsetsTextField new];
//    self.phoneNumTextF.placeholder = @"手机号";
    NSMutableAttributedString *phoneplaceholderString = [[NSMutableAttributedString alloc] initWithString:@"手机号" attributes:@{NSForegroundColorAttributeName : RGB_VALUE(0xA5A5A5)}];
    self.phoneNumTextF.attributedPlaceholder = phoneplaceholderString;
    self.phoneNumTextF.font = JSS_MEDIUM_FONT_7;
//    self.phoneNumTextF.textColor = RGB_VALUE(0xA5A5A5);
    self.phoneNumTextF.layer.masksToBounds = YES;
    self.phoneNumTextF.layer.cornerRadius = 14;
    self.phoneNumTextF.backgroundColor = UIColor.whiteColor;
    [bgImg addSubview:self.phoneNumTextF];
    [self.phoneNumTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.top.equalTo(titleLabel.mas_bottom).offset(19);
        make.right.offset(-147);
        make.height.mas_equalTo(56);
    }];
    
    self.userNameTextF = [InsetsTextField new];
//    self.userNameTextF.placeholder = @"用户名";
    NSMutableAttributedString *nameplaceholderString = [[NSMutableAttributedString alloc] initWithString:@"用户名" attributes:@{NSForegroundColorAttributeName : RGB_VALUE(0xA5A5A5)}];
    self.userNameTextF.attributedPlaceholder = nameplaceholderString;
    self.userNameTextF.font = JSS_MEDIUM_FONT_7;
//    self.userNameTextF.textColor = RGB_VALUE(0xA5A5A5);
    self.userNameTextF.layer.masksToBounds = YES;
    self.userNameTextF.layer.cornerRadius = 14;
    self.userNameTextF.backgroundColor = UIColor.whiteColor;
    [bgImg addSubview:self.userNameTextF];
    [self.userNameTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.top.equalTo(self.phoneNumTextF.mas_bottom).offset(10);
        make.right.offset(-28);
        make.height.mas_equalTo(56);
    }];
    
    self.sliderBGView = [[UIView alloc] init];
    self.sliderBGView.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    self.sliderBGView.layer.cornerRadius = 14;
    self.sliderBGView.layer.masksToBounds = YES;
    [bgImg addSubview:self.sliderBGView];
    [self.sliderBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.top.equalTo(self.userNameTextF.mas_bottom).offset(10);
        make.right.offset(-28);
        make.height.mas_equalTo(56);
    }];
    
    self.sliderView = [[UIView alloc] init];
    self.sliderView.backgroundColor = RGB_VALUE(0xDC0000);
    self.sliderView.layer.cornerRadius = 14;
    self.sliderView.layer.masksToBounds = YES;
    [self.sliderBGView addSubview:self.sliderView];
    [self.sliderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.offset(0);
        make.width.mas_equalTo(56);
    }];
    
    self.sliderImg = [[UIImageView alloc] init];
    self.sliderImg.image = [UIImage imageNamed:@"register_slider"];
    self.sliderImg.hidden = YES;
    [self.sliderView addSubview:self.sliderImg];
    [self.sliderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.sliderView);
        make.width.height.mas_equalTo(16);
    }];
    
    UILabel *exlpainLabel = [UILabel new];
    exlpainLabel.text = @"将滑块拖至最右边完成验证";
    exlpainLabel.font = JSS_MEDIUM_FONT(17);
    exlpainLabel.textColor = RGB_VALUE(0xF8F7F8);
    exlpainLabel.textAlignment = NSTextAlignmentCenter;
    [bgImg addSubview:exlpainLabel];
    [exlpainLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.sliderView.mas_bottom).offset(10);
        make.left.offset(35);
        make.right.offset(-35);
        make.height.mas_equalTo(24);
    }];
    
    self.verificationCodeTextF = [InsetsTextField new];
//    self.verificationCodeTextF.placeholder = @"验证码";
    NSMutableAttributedString *verificationCodeplaceholderString = [[NSMutableAttributedString alloc] initWithString:@"验证码" attributes:@{NSForegroundColorAttributeName : RGB_VALUE(0xA5A5A5)}];
    self.verificationCodeTextF.attributedPlaceholder = verificationCodeplaceholderString;
    self.verificationCodeTextF.font = JSS_MEDIUM_FONT_7;
//    self.verificationCodeTextF.textColor = RGB_VALUE(0xA5A5A5);
    self.verificationCodeTextF.layer.masksToBounds = YES;
    self.verificationCodeTextF.layer.cornerRadius = 14;
    self.verificationCodeTextF.backgroundColor = UIColor.whiteColor;
    [bgImg addSubview:self.verificationCodeTextF];
    [self.verificationCodeTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.top.equalTo(exlpainLabel.mas_bottom).offset(10);
        make.right.offset(-28);
        make.height.mas_equalTo(56);
    }];
    
    self.verificationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.verificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.verificationBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    [self.verificationBtn.titleLabel setFont:JSS_MEDIUM_FONT_7];
    self.verificationBtn.layer.masksToBounds = YES;
    self.verificationBtn.layer.cornerRadius = 14;
    self.verificationBtn.backgroundColor = RGB_VALUE(0xFFB100);
    [self.verificationBtn addTarget:self action:@selector(verificationBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgImg addSubview:self.verificationBtn];
    [self.verificationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.phoneNumTextF.mas_right).offset(6);
        make.centerY.equalTo(self.phoneNumTextF);
        make.right.offset(-28);
        make.height.equalTo(self.phoneNumTextF);
    }];
    
    self.passwordTextF = [InsetsTextField new];
//    self.passwordTextF.placeholder = @"设置密码";
    NSMutableAttributedString *passwordplaceholderString = [[NSMutableAttributedString alloc] initWithString:@"设置密码" attributes:@{NSForegroundColorAttributeName : RGB_VALUE(0xA5A5A5)}];
    self.passwordTextF.attributedPlaceholder = passwordplaceholderString;
    self.passwordTextF.font = JSS_MEDIUM_FONT_7;
//    self.passwordTextF.textColor = RGB_VALUE(0xA5A5A5);
    self.passwordTextF.layer.masksToBounds = YES;
    self.passwordTextF.layer.cornerRadius = 14;
    self.passwordTextF.backgroundColor = UIColor.whiteColor;
    self.passwordTextF.secureTextEntry = YES;
    [bgImg addSubview:self.passwordTextF];
    [self.passwordTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.top.equalTo(self.verificationCodeTextF.mas_bottom).offset(10);
        make.right.offset(-28);
        make.height.mas_equalTo(56);
    }];
    
    self.ensurePasswordTextF = [InsetsTextField new];
//    self.ensurePasswordTextF.placeholder = @"确认密码";
    NSMutableAttributedString *ensurepasswordplaceholderString = [[NSMutableAttributedString alloc] initWithString:@"确认密码" attributes:@{NSForegroundColorAttributeName : RGB_VALUE(0xA5A5A5)}];
    self.ensurePasswordTextF.attributedPlaceholder = ensurepasswordplaceholderString;
    self.ensurePasswordTextF.font = JSS_MEDIUM_FONT_7;
//    self.ensurePasswordTextF.textColor = RGB_VALUE(0xA5A5A5);
    self.ensurePasswordTextF.layer.masksToBounds = YES;
    self.ensurePasswordTextF.layer.cornerRadius = 14;
    self.ensurePasswordTextF.backgroundColor = UIColor.whiteColor;
    self.ensurePasswordTextF.secureTextEntry = YES;
    [bgImg addSubview:self.ensurePasswordTextF];
    [self.ensurePasswordTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.top.equalTo(self.passwordTextF.mas_bottom).offset(10);
        make.right.offset(-28);
        make.height.mas_equalTo(56);
    }];
    
    UIButton *protocalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [protocalBtn.titleLabel setFont:JSS_MEDIUM_FONT(17)];
    [protocalBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    [protocalBtn setTitle:@"注册即代表同意用户使用协议" forState:UIControlStateNormal];
    [protocalBtn setImage:[UIImage imageNamed:@"register_protocalSelect"] forState:UIControlStateSelected];
    [protocalBtn setImage:[UIImage imageNamed:@"register_protocalNoSelect"] forState:UIControlStateNormal];
    [protocalBtn layoutButtonWithEdgeInsetsStyle:DVButtonEdgeInsetsStyleLeft imageTitleSpace:18];
    [protocalBtn addTarget:self action:@selector(protocalBtn:) forControlEvents:UIControlEventTouchUpInside];
    protocalBtn.adjustsImageWhenHighlighted=NO;
    [bgImg addSubview:protocalBtn];
    [protocalBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.ensurePasswordTextF.mas_bottom).offset(16);
        make.left.offset(28);
        make.right.offset(-89);
        make.height.mas_equalTo(24);
    }];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setTitle:@"注册" forState:UIControlStateNormal];
    [loginBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    [loginBtn.titleLabel setFont:JSS_MEDIUM_FONT_7];
    loginBtn.backgroundColor = RGB_VALUE(0xDC0000);
    loginBtn.layer.masksToBounds = YES;
    loginBtn.layer.cornerRadius = 14;
    [loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgImg addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(protocalBtn.mas_bottom).offset(18);
        make.right.offset(-28);
        make.left.offset(28);
        make.height.mas_equalTo(56);
    }];
    
    UIButton *bottomLabel = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomLabel setTitle:@"已经拥有账号 ？马上登录" forState:UIControlStateNormal];
    [bottomLabel setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    [bottomLabel.titleLabel setFont:JSS_MEDIUM_FONT_7];
    [bottomLabel addTarget:self action:@selector(bottomLabelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgImg addSubview:bottomLabel];
    [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(loginBtn.mas_bottom).offset(24);
        make.centerX.offset(0);
        make.height.mas_equalTo(24);
        make.width.mas_equalTo(202);
    }];
    
    if (@available(iOS 11.0, *)) {
        bgScrollview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [bgScrollview mas_makeConstraints:^(MASConstraintMaker *make) {
             // 注意点2：
        make.bottom.equalTo(bottomLabel.mas_bottom).offset(62);
    }];
    [bgImg mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.top.offset(0);
        make.width.mas_equalTo(kDeviceWidth);
        make.bottom.equalTo(bgScrollview.mas_bottom).offset(162);
    }];
    
    UIPanGestureRecognizer *panG = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panSliderView:)];
    [self.sliderView addGestureRecognizer:panG];
}

- (void)panSliderView:(UIPanGestureRecognizer *)sender
{
    UIView *view = sender.view;
    CGFloat offsetX = [(UIPanGestureRecognizer *)sender translationInView:view].x;
    if (sender.state == UIGestureRecognizerStateBegan) {
        
    } else if (sender.state == UIGestureRecognizerStateChanged) {
        
        NSLog(@"%.f",offsetX);
        if (offsetX <=0) {
            return;
        }
        if (offsetX >= (kDeviceWidth - 112)) {
            [self.sliderView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.offset(kDeviceWidth - 112);
            }];
            NSLog(@"=====1");
        } else {
            [self.sliderView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.offset(offsetX);
            }];
            NSLog(@"=====2");
        }
        
    } else if (sender.state == UIGestureRecognizerStateEnded) {
        if (offsetX >= (kDeviceWidth - 112)) {
            [self.sliderView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.offset(kDeviceWidth - 112);
            }];
            self.sliderView.userInteractionEnabled = NO;
            self.sliderBGView.backgroundColor = RGB_VALUE(0xFF7676);
            self.sliderImg.hidden = NO;
            NSLog(@"=====3");
            self.isVerification = YES;
        } else {
            [self.sliderView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.offset(0);
            }];
            NSLog(@"=====4");
        }
    }
}

- (void)backBtnClick
{
    [self pop];
}

// 获取验证码
- (void)verificationBtnClick:(UIButton *)sender
{
    if (!self.isVerification) {
        [self showMessage:@"请先滑动滑块完成验证"];
        return;
    }
    
    if (NULLString(self.phoneNumTextF.text)) {
        [self showMessage:@"手机号不能为空"];
        return;
    }
    [self.view endEditing:YES];
    NSDictionary *paramDic = @{@"mobile":self.phoneNumTextF.text};
    [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypePost URLString:@"identify" parameters:paramDic done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        NSTimeInterval seconds =120;
        NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:seconds];// 最后期限
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
        dispatch_source_t _sometimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
        dispatch_source_set_timer(_sometimer, dispatch_walltime(NULL,0),1.0*NSEC_PER_SEC,0);// 每秒执行一次
        dispatch_source_set_event_handler(_sometimer, ^{
            int interval = [endTime timeIntervalSinceNow];
            if(interval >0) {// 更新倒计时
                NSString *timeStr = [NSString stringWithFormat:@"%d秒内有效", interval];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [sender setTitle:timeStr forState:UIControlStateNormal];                     sender.userInteractionEnabled =NO;
                    [sender setTitleColor:RGB_VALUE(0xA5A5A5) forState:UIControlStateNormal];
                });
            }else{
                // 倒计时结束，关闭
                
                dispatch_source_cancel(_sometimer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [sender setTitle:@"获取验证码"forState:UIControlStateNormal];
                    [sender setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];                sender.userInteractionEnabled =YES;
                });
            }
        });
        dispatch_resume(_sometimer);
        
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

// 注册
- (void)loginBtnClick:(UIButton *)sender
{
    if (!self.isVerification) {
        [self showMessage:@"请先滑动滑块完成验证"];
        return;
    }
    if (!self.isSelectProtocal) {
        [self showMessage:@"请先同意用户使用协议"];
        return;
    }
    if (NULLString(self.phoneNumTextF.text)) {
        [self showMessage:@"手机号不能为空"];
        return;
    }
    if (NULLString(self.userNameTextF.text)) {
        [self showMessage:@"用户名不能为空"];
        return;
    }
    if (NULLString(self.verificationCodeTextF.text)) {
        [self showMessage:@"验证码不能为空"];
        return;
    }
    if (NULLString(self.passwordTextF.text)) {
        [self showMessage:@"密码不能为空"];
        return;
    }
    if (NULLString(self.ensurePasswordTextF.text)) {
        [self showMessage:@"确认密码不能为空"];
        return;
    }
    if (![self.passwordTextF.text isEqualToString:self.ensurePasswordTextF.text]) {
        [self showMessage:@"两次密码不一致"];
        return;
    }
    NSDictionary *paramDic = @{
        @"password":self.passwordTextF.text,
        @"password1":self.ensurePasswordTextF.text,
        @"mobile":self.phoneNumTextF.text,
        @"code":self.verificationCodeTextF.text,
        @"username":self.userNameTextF.text,
    };
    [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypePost URLString:@"login" parameters:paramDic done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        [[DVUserManager shareManager] updateUserInfo:responseObject[@"data"]];
        NSDictionary *userInfo = [DVUserManager shareManager].userInfo;
        NSLog(@"登录成功之后的个人token%@",userInfo);
            //    DVUserManager *manager = [DVUserManager shareManager];
            //    [manager setRootViewController:manager.tabBarController];
        
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

// 协议
- (void)protocalBtn:(UIButton *)sender
{
    sender.selected = !sender.selected;
    self.isSelectProtocal = sender.selected;
}

///  已经拥有账号 ？马上登录
- (void)bottomLabelBtnClick:(UIButton *)sender
{
    [self pop];
}
@end
